package com.google.project.client.Operator;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.DailyReportService;
import com.google.project.client.Service.DailyReportServiceAsync;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectStaffService;
import com.google.project.client.Service.ProjectStaffServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDTO;
import com.google.project.shared.ProjectStaffDTO;

public class OPTDailyReportList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button btnCreateDailyReport;
	@UiField(provided = true) CellTable<DailyReportDTO> ctbDailyReport = new CellTable<DailyReportDTO>();
	@UiField SimplePager pager;
	@UiField Button btnSearch;
	@UiField ListBox cboCate;
	@UiField DateBox dbFromDate;
	@UiField DateBox dbToDate;

	interface Binder extends UiBinder<Widget, OPTDailyReportList> {
	}

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final DailyReportServiceAsync dailyReportService = GWT
			.create(DailyReportService.class);
	private final ProjectStaffServiceAsync prjStaff = GWT
			.create(ProjectStaffService.class);
	public String currentProjID = "";
	public String userID = "";
	private List<ProjectStaffDTO> listPrjStaffDTO = new ArrayList<ProjectStaffDTO>();
	private List<DailyReportDTO> listDailyReportDTO = new ArrayList<DailyReportDTO>();

	public OPTDailyReportList() {
		initWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		initTable();
		getUserID();
		bindData();

	}

	public void initCboStatus() {
		cboCate.addItem("---Tất cả---", "-1");
		cboCate.addItem("Chưa đọc", "2");
		cboCate.addItem("Đã đọc", "0");
		cboCate.addItem("Đã huỷ", "3");
		cboCate.setSelectedIndex(1);
	}

	// get all employee of projectStaff
	public void bindData() {
		prjStaff.getAllPrjStaff(new AsyncCallback<List<ProjectStaffDTO>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(List<ProjectStaffDTO> result) {
				for (ProjectStaffDTO projectStaffDTO : result) {
					listPrjStaffDTO.add(projectStaffDTO);

				}
				getProjectID();
				initCboStatus();
			}
		});

	}

	// get userID from session
	public void getUserID() {
		loginService.getUserID(new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(String result) {
				userID = result;
				getProjectID();

			}
		});
	}

	// get current projectID by status=1
	public void getProjectID() {
		Boolean condition = true;

		List<ProjectStaffDTO> temple = new ArrayList<ProjectStaffDTO>();
		for (ProjectStaffDTO staff : listPrjStaffDTO) {

			if (userID != null) {
				condition = condition
						&& (staff.getUserId().equals(userID) && (staff
								.getStatus() == 1));

			}
			if (condition) {
				temple.add(staff);
				currentProjID = staff.getProjectId();
				break;
			}
			condition = true;
		}
		if (currentProjID != null && !currentProjID.equalsIgnoreCase("")) {
			getDailyReportByProject(2); // lay report co
										// fromUserID=userID(login) va
										// status=2-phan hoi tu pm
		}
	}

	// init ctbReportTaskList
	public void initTable() {
		TextColumn<DailyReportDTO> index = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				return report.getIndex() +"";
			}
		};
		Column<DailyReportDTO, String> projectColumn = new Column<DailyReportDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(DailyReportDTO report) {
				return report.getProjectDTO().getProjectName();
			}
		};
		projectColumn
		.setFieldUpdater(new FieldUpdater<DailyReportDTO, String>() {

			@Override
			public void update(int index,
					DailyReportDTO dailyReportDTO, String value) {
				OPTEntrypoint.get()
						.OPTDailyReportDetail(dailyReportDTO);
			}
		});
		TextColumn<DailyReportDTO> reportDateColumn = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				return CommonFuntion.convertToDate(new Date(report
						.getReportForDate()));
			}
		};
		TextColumn<DailyReportDTO> createdOnDate = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				return CommonFuntion.convertToDate(new Date(report
						.getCreatedOnDate()));
			}
		};
		TextColumn<DailyReportDTO> numOfTask = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				return report.getNumOfTask()+"" ;
			}
		};
		TextColumn<DailyReportDTO> status = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				String result="";
				if(report.getStatus()==0 || report.getStatus()==1){
					result+="Đã đọc";
				}else if(report.getStatus()==2){
					result+="Chưa đọc";
				}else if(report.getStatus()==3){
					result+="Đã hủy";
				}
				return result ;
			}
		};
		projectColumn.setCellStyleNames("celltable");
		ctbDailyReport.addColumn(index, "STT");
		ctbDailyReport.addColumn(projectColumn, "Dự án");
		ctbDailyReport.addColumn(reportDateColumn, "Báo Cáo Ngày");
		ctbDailyReport.addColumn(createdOnDate, "Ngày Gửi");
		ctbDailyReport.addColumn(numOfTask, "Số Công Việc");
		ctbDailyReport.getColumn(ctbDailyReport.getColumnIndex(numOfTask)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		ctbDailyReport.addColumn(status, "Tình Trạng");
		ctbDailyReport.setStyleName("ttable");
	}

	protected void LoadData(List<DailyReportDTO> dailyReportList) {

		// TODO Auto-generated method stub
		ListDataProvider<DailyReportDTO> dataProvider = new ListDataProvider<DailyReportDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbDailyReport);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index=1;
		List<DailyReportDTO> list = dataProvider.getList();
		for (DailyReportDTO dailyDetail : dailyReportList) {
			dailyDetail.setIndex(index);
			list.add(dailyDetail);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbDailyReport);
		pager.setPageSize(5);
	}

	// lấy về báo cáo ngày theo ProjectID, status
	public void getDailyReportByProject(final int statusReport) {
		// listDailyReportDTO=new
		dailyReportService.getDailyReportByProjectId(currentProjID,
				new AsyncCallback<List<DailyReportDTO>>() {

					@Override
					public void onSuccess(List<DailyReportDTO> result) {
						Boolean condition = true;
						for (DailyReportDTO dailyReportDTO : result) {
							if (cboCate.getValue(cboCate.getSelectedIndex()) != null
									&& Integer.parseInt((cboCate
											.getValue(cboCate
													.getSelectedIndex()))) != -1) {
								condition = condition
										&& (dailyReportDTO.getStatus() == statusReport);
							}
							if(dbFromDate.getValue()!=null){
								Long fromDate=CommonFuntion.removeTime( dbFromDate.getValue());
								condition=condition && (fromDate<=CommonFuntion.removeTime(new Date(dailyReportDTO.getReportForDate())));
							}
							if(dbToDate.getValue()!=null){
								Long toDate=CommonFuntion.removeTime(dbToDate.getValue());
								condition=condition && (CommonFuntion.removeTime(new Date(dailyReportDTO.getReportForDate()))<toDate);
							}
							if (condition
									&& dailyReportDTO.getFromUserID().equals(
											userID)) {
								listDailyReportDTO.add(dailyReportDTO);
							}
							condition = true;
						}

						if (listDailyReportDTO != null) {
							LoadData(listDailyReportDTO);
						}
					}

					@Override
					public void onFailure(Throwable caught) {
						// Window.alert("fail");

					}
				});
	}

	@UiHandler("btnCreateDailyReport")
	void onBtnCreateDailyReportClick(ClickEvent event) {
		OPTEntrypoint.get().OPTCreateDailyReport(userID, currentProjID);
	}

	@UiHandler("cboCate")
	void onCboCateChange(ChangeEvent event) {
		listDailyReportDTO.clear();
		int value = Integer.parseInt(cboCate.getValue(cboCate
				.getSelectedIndex()));
		if (value == -1) {
			getDailyReportByProject(-1);
		} else if (value == 0) {
			getDailyReportByProject(0);
			getDailyReportByProject(1);
		} else if (value == 2) {
			getDailyReportByProject(value);
		}else if (value == 3) {
			getDailyReportByProject(value);
		}
	}
	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		listDailyReportDTO.clear();
		if(dbFromDate.getValue()!=null && dbToDate.getValue()!=null){
			if(dbFromDate.getValue().getTime()>dbToDate.getValue().getTime()){
				Window.alert("Ngày sau phải lớn hơn ngày trước!");
				listDailyReportDTO.clear();
			}else{
				getDailyReportByProject(-1);
			}
		}else{
			int value = Integer.parseInt(cboCate.getValue(cboCate
					.getSelectedIndex()));
			if (value == -1) {
				getDailyReportByProject(-1);
			} else if (value == 0) {
				getDailyReportByProject(0);
				getDailyReportByProject(1);
			} else if (value == 2) {
				getDailyReportByProject(value);
			} else if (value == 3) {
				getDailyReportByProject(value);
			}
		}
		
	}
	
}
